var url = 'https://www.aiordos.com'
var socket = io(url);
var msgIpt = document.getElementById('msg')
var send = document.getElementById('send')
var msgShow = document.getElementById('chat-msg')

var username = prompt("亲，请给自己起个昵称","dell");
var roomid = prompt("请输入房间号",1);


msgIpt.addEventListener('keyup',function(event){
    if (event.ctrlKey && event.keyCode == 13){
        sendMsg()
    }
})
send.addEventListener('click', function (e) {
    sendMsg()
})

/**
 * 发送消息
 */
 function sendMsg(){
    if (!msgIpt.value) {
        return;
    }

    var val = "我：" + msgIpt.value
    // 发送消息
    socket.emit('message',roomid, msgIpt.value)

    msgIpt.value = ''
    addMessage('send',val)
}

// client-side
socket.on("connect", (e) => {
    console.log(socket.id); 
});

socket.on("disconnect", (e) => {
    console.log(socket.id); // undefined
});

socket.emit('join',roomid,username);
// 加入房间
socket.on("joined", (user,id)=>{
    var msg = user + "加入房间：" + id
    addMessage('sys',msg)
})
// 离开房间
socket.on('leaved',(data) =>{
    
})
// 接收到消息
socket.on('message', (data,user) => {
    var msg = user + ":" + data
    addMessage('get',msg)
})

function addMessage(type,msg){
    var p = document.createElement('p')
    if(type === 'send'){
        p.classList.add('send-msg')
    }else if(type === 'get'){
        p.classList.add('get-msg')
    }else {
        p.classList.add('sys-msg')
    }
    
    p.textContent = msg
    msgShow.appendChild(p)
    msgShow.scrollTo(0, msgShow.scrollHeight);
    msgIpt.focus();
}

